package com.yf.system.modules.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yf.base.utils.BeanMapper;
import com.yf.notify.modules.notify.dto.request.MsgReceiverDTO;
import com.yf.notify.modules.notify.dto.request.MsgSendDTO;
import com.yf.notify.modules.notify.service.MsgService;
import com.yf.system.modules.user.dto.request.UserMsgReqDTO;
import com.yf.system.modules.user.entity.SysUser;
import com.yf.system.modules.user.service.SysUserService;
import com.yf.system.modules.user.service.UserMsgService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserMsgServiceImpl implements UserMsgService {

    @Autowired
    private MsgService msgService;

    @Autowired
    private SysUserService sysUserService;

    @Override
    public void sendMsg(UserMsgReqDTO reqDTO) {

        List<MsgReceiverDTO> tos = new ArrayList<>();

        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .select(SysUser::getId, SysUser::getRealName, SysUser::getMobile, SysUser::getEmail)
                .in(SysUser::getId, reqDTO.getUserIds());
        List<SysUser> list = sysUserService.list(wrapper);

        for(SysUser item: list){
            MsgReceiverDTO dto = new MsgReceiverDTO();
            // 昵称
            dto.setUserId(item.getId());
            dto.setRealName(item.getRealName());
            // 邮件
            if(StringUtils.isNotBlank(item.getEmail()) && reqDTO.getUseEmail()!=null && reqDTO.getUseEmail()){
                dto.setEmail(item.getEmail());
            }
            // 手机
            if(StringUtils.isNotBlank(item.getMobile()) && reqDTO.getUseSms()!=null && reqDTO.getUseSms()){
                dto.setMobile(item.getMobile());
            }
            // 覆盖
            tos.add(dto);
        }

        // 调用消息中心
        MsgSendDTO dto = new MsgSendDTO();
        BeanMapper.copy(reqDTO, dto);
        dto.setTos(tos);
        dto.setUseIm(reqDTO.getUseIm()==null?false: reqDTO.getUseIm());
        dto.setUseSms(reqDTO.getUseSms()==null?false: reqDTO.getUseSms());
        dto.setUseEmail(reqDTO.getUseEmail()==null?false: reqDTO.getUseEmail());
        msgService.sendNotify(dto);
    }
}
